<?php

/**
 * alltosun.com  dealers_helper.php
 * ============================================================================
 * 版权所有 (C) 2009-2013 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 王德康 (wangdk@alltosun.com) $
 * $Date: 2016-1-24 下午4:34:20 $
 * $Id$
 */
class dealers_helper
{
    /**
     * 是否存在未处理完的订单
     * @param unknown_type $user_store_id
     * @return Ambigous <number, number>|boolean
     */
    public static function is_unset_order_user_store($user_store_id) {
        // 所有分店
        $store_list = store_helper::get_user_store_list_id($user_store_id);
        if ($store_list) {

            // 所有分店id
            $store_ids = array();
            foreach ($store_list as $val) {
                $store_ids[] = $val['id'];
            }
            // 总店或者分店存在订单都不能迁移
            return $num = order_helper::get_order_num_by_progress(array(1, 3, 5), 5, array(
                'store_id' => $store_ids,
                'is_enable' => array(0, 1)
            ));
        }

        return false;
    }

    /**
     * 返回合伙人或者市场人员旗下未绑定设备列表
     * @param unknown_type $owner_id
     * @param unknown_type $marketing_id
     * @return unknown
     */
    public static function get_unset_device_store_list($owner_id, $marketing_id) {
        $unset_store_device_ids = array();
        $user_store_list = store_helper::get_user_store_list_by_id($owner_id, $marketing_id);
        if ($user_store_list) {
            foreach ($user_store_list as $v) {
                if (store_helper::is_user_store_bind_device($v['user_id'])) {
                    $unset_store_device_ids[] = $v['id'];
                }
            }
        }
        return $unset_store_device_ids;
    }

    /**
     * 获取经销商为调过价的店铺
     * @param unknown_type $user_id
     */
    public static function get_unset_price_store_list($owner_id, $marketing_id) {
        $unset_store_price_ids = array();
        $user_store_list = store_helper::get_user_store_list_by_id($owner_id, $marketing_id);
        if ($user_store_list) {
            foreach ($user_store_list as $v) {
                if (store_helper::is_store_unset_price($v['id'])) {
                    $unset_store_price_ids[] = $v['id'];
                }
            }
        }
        return $unset_store_price_ids;
    }

    /**
     *  获取超过7天未操作的数据
     * @param unknown_type $user_id
     * @param unknown_type $store_id
     * @param unknown_type $type
     * @return boolean
     */
    public static function get_last_7day($user_id, $type) {
        $filter['user_id'] = $user_id;
        $filter['type'] = $type;

        $info = _model('last_change_record')->read($filter);
        if (!$info) {
            return false;
        }

        if (strtotime($info['add_time']) <= time() - 60 * 60 * 24 * 7) {
            return 1;
        }

        return 0;
    }

    /**
     * 保存最后的记录，最后一次盘点，最后一次...等等
     * @param unknown_type $user_id
     * @param unknown_type $store_id
     * @param unknown_type $type
     */
    public static function save_last_change_record($user_id, $store_id, $type) {
        $filter['user_id'] = $user_id;
        $filter['store_id'] = $store_id;
        $filter['type'] = $type;

        $date = date('Y-m-d H:i:s');
        $record_info = _model('last_change_record')->read($filter);
        if (!$record_info) {

            $data = $filter;
            $data['add_time'] = $date;

            return _model('last_change_record')->create($data);
        }

        return _model('last_change_record')->update($record_info['id'], array('add_time' => $date));
    }

    /**
     * 获取经销商的默认仓库信息
     * @param unknown $user_id
     */
    public static function get_default_dealer_address($user_id, $filter = array()) {
        if (!$user_id) {
            return array();
        }

        $filter['user_id'] = $user_id;
        $filter['is_default'] = 1;

        return _uri('dealer_address', $filter);
    }

    /**
     * 数据迁移接口需要返回市场人员列表的时候加上经销商
     * @param unknown_type $user_info
     * @return string
     */
    public static function market_list_add_agency_info($user_info) {
        $agency_info['id'] = '-1';
        $agency_info['avatar'] = '';
        $agency_info['mobile'] = '';
        $agency_info['realname'] = $user_info['realname'] . '(合伙人)';
        $agency_info['user_name'] = $user_info['user_name'];
        $agency_info['gender'] = 1;
        $agency_info['all_sales_money'] = '0';
        $agency_info['all_sales_num'] = '0';
        $agency_info['no_deliver_num'] = '0';
        $agency_info['store_num'] = '0';

        return $agency_info;
    }

    /**
     * 数据迁移页面展现的市场人员列表
     * @param unknown_type $realname
     * @return string
     */
    public static function market_list_add_tag($realname) {
        return $realname . '(市场人员)';
    }

    /**
     * 市场人员列表的统计信息
     * @param unknown_type $marketing_id
     * @param unknown_type $tmp_user_info
     * @return [type]
     */
    public static function market_stat_info($marketing_id, &$tmp_user_info) {
        // 历史业绩
        $tmp_user_info['all_sales_money'] = _widget('stat.api_stat')->get_marketing_sale_data($marketing_id, 'all', 'price');
        $tmp_user_info['all_sales_money'] = (string)$tmp_user_info['all_sales_money'];

        // 历史销量数目
        $tmp_user_info['all_sales_num'] = _widget('stat.api_stat')->get_marketing_sale_data($marketing_id, 'all', 'box');

        // 本月业绩
        $tmp_user_info['month_sales_money'] = _widget('stat.api_stat')->get_marketing_sale_data($marketing_id, 'curr_month', 'price');
        // 本月销量数目
        $tmp_user_info['month_sales_num'] = _widget('stat.api_stat')->get_marketing_sale_data($marketing_id, 'curr_month', 'box');

        // 还没有配送的订单
        $tmp_user_info['no_deliver_num'] = stat_helper::get_marketing_no_deliver_num($marketing_id);

        // 负责店铺的数目
        //         $tmp_user_info['store_num'] = stat_helper::get_marketing_store_num($marketing_id);
        $tmp_user_info['store_num'] = store_helper::get_marketing_user_store_num($marketing_id);

        return $tmp_user_info;
    }

    private function get_store_order($store_ids) {
        $filter['store_id'] = $store_ids;
        $filter['progress'] = array(1, 3, 5);
        $filter['type'] = 5;
        return _model('order')->getTotal($filter);
    }

    /**
     * 总店(包括分店)转义到新的市场人员旗下
     * @param unknown_type $owner_id 总店的用户ID
     * @param unknown_type $market_id 市场人员ID
     * @param unknown_type $agency_id 经销商ID
     */
    public static function user_store_to_market($owner_id, $market_id, $agency_id = 0) {
        // 总店
        $user_store_info = store_helper::get_user_store_info_by_id($owner_id);
        if ($user_store_info) {

            // 不能重复迁移
            if ($user_store_info['marketing_id'] == $market_id) {
                return array(false, '当前门店已经属于该市场人员，请勿重复迁移!');
            }

            //$no_deliver_num = order_helper::get_order_num_by_progress(array(1, 3, 5), 5, array('user_id'=>$owner_id, 'is_enable'=>array(0, 1)));
            // 分店
            $store_list = store_helper::get_user_store_list_id($user_store_info['user_id']);
            if ($store_list) {

                // 所有分店id
                $store_ids = array();
                foreach ($store_list as $val) {
                    $store_ids[] = $val['id'];
                }

                // 总店或者分店存在订单都不能迁移
                $order_num = order_helper::get_order_num_by_progress(array(1, 3, 5), 5, array(
                    'store_id' => $store_ids,
                    'is_enable' => array(0, 1)
                ));
                if ($order_num) {
                    return array(false, '门店有存在未完成的订单!');
                }
                return store_helper::update_store_list_to_market($user_store_info['id'], $store_list, $market_id, $agency_id);
            }
        }

        return array(false, '要迁移的门店不存在!');;
    }


    /**
     * 补充经销商商仓库地址信息，如果仓库地址未补充手机号和收货人，默认收货人和手机号是经销商的
     * @param unknown_type $dealer_user_id 经销商用户ID
     * @param unknown_type $addres_id 仓库ID
     * @param unknown_type $info 填充的数组
     * @return unknown
     */
    public static function get_dealer_address_info($dealer_user_id, $addres_id, &$info = array()) {
        if (!$addres_id) {
            return $info;
        }

        $dealer_address_info = _uri('dealer_address', $addres_id);
        if ($dealer_address_info) {
            $info['dealer_address'] = $dealer_address_info['dealer_address'];

            $info['province'] = $dealer_address_info['province_code'];
            $info['city'] = $dealer_address_info['city_code'];
            $info['district'] = $dealer_address_info['county_code'];
        }

        return $info;
    }

    /**
     * 旗下员工信息
     * @param unknown_type $agency_id
     * @return multitype:Ambigous <multitype:, string, unknown, Obj, mixed>
     */
    public static function get_dealers_staff_info($market_id) {
        $market_info = _model('user_marketing')->read(array('marketing_id' => $market_id));
        return $market_info;
    }

    /**
     * 旗下员工列表
     * @param unknown_type $agency_id
     * @return multitype:Ambigous <multitype:, string, unknown, Obj, mixed>
     */
    public static function get_dealers_staff_list($agency_id) {
        $market_user_list = array();
        $market_filter['agency_id'] = $agency_id;
        $market_list = _model('user_marketing')->getList($market_filter);
        if ($market_list) {
            foreach ($market_list as $market_val) {
                $market_user_list[] = user_helper::get_user_info($market_val['marketing_id']);
            }
        }

        return $market_user_list;
    }


    /**
     * 获取经销商的等级
     * @param unknown_type $user_id
     */
    public static function get_dealers_level($user_id) {
        $dealers_info = user_helper::get_user_info($user_id);
        if ($dealers_info) {
            return $dealers_info['dealer_level'];
        }

        return false;
    }

    /**
     * 获取当前经销商的价格差价，
     * 二级经销商的价格在原价 +5,一级经销商可以设置下属经销商是否可以+加价进货
     * @param unknown_type $sku_id
     * @param unknown_type $goods_id
     * @param unknown_type $user_id
     */
    public static function get_dealers_goods_diff_price($user_id, $sku_id) {
        $diff_price = 0;
        $level = self::get_dealers_level($user_id);

        $user_info = user_helper::get_user_info($user_id);
        if ($user_info) {

            // 必须是一级经销商设置旗下的二级经销商加价
            if ($user_info['is_diff_price'] && $level == 2) {

                // 获取当前sku的二级经销商的差价
                $diff_price = goods_helper::get_diff_price_by_id($sku_id);
                return $diff_price;
            }
        }
        return $diff_price;
    }

    /**
     * 获取二级经销商兑换差价
     *
     * @param $user_id
     * @param $sku_id
     * @return int|string
     */
    public static function get_dealers_goods_diff_bbcoin($user_id, $sku_id) {
        $diff_bbcoin = 0;
        $level = self::get_dealers_level($user_id);

        $user_info = user_helper::get_user_info($user_id);
        if ($user_info) {

            // 必须是一级经销商设置旗下的二级经销商加价
            if ($user_info['is_diff_price'] && $level == 2) {

                // 获取当前sku的二级经销商的差价
                $diff_bbcoin = goods_helper::get_diff_bbcoin_by_id($sku_id);
                return $diff_bbcoin;
            }
        }
        return $diff_bbcoin;
    }

    /**
     * 根据商铺ID获取经销商的用户信息
     * @param unknown_type $store_id
     * @wangdk
     */
    public static function get_dealers_user_info($store_id) {
        $store_info = store_helper::get_store($store_id);
        if (!$store_info) {
            return false;
        }

        if (!$store_info['agency_id']) {
            return false;
        }

        return user_helper::get_user_info($store_info['agency_id']);
    }

    /**
     * 统计经销商所有库存总量
     */
    public static function get_dealer_stock($dealer_ids = array()) {
        if (!$dealer_ids) {
            return 0;
        }

        $filter['user_id'] = $dealer_ids;

        $stock_list = _model('store_goods_sku')->getFields('stock', $filter);
        return array_sum($stock_list);
    }

    /**
     * 获取经销商仓库地址列表
     * @param $dealer_id 经销商用户id
     * @param $page_no 页码数
     * @param $page_num 每页显示条数
     */
    public static function get_dealer_address_list($dealer_id, $page_no = 1, $page_num = 20) {

        $filter = array();
        $filter['user_id'] = $dealer_id;
        $filter['status'] = 1;

        // 获取用户名
        $user_info = user_helper::get_user_info($dealer_id);
        // 获取此合伙人合伙人的地区信息
        $dealer_address_list = get_data_list('dealer_address', $filter, 'ORDER BY `province_code`,`city_code`,`county_code`', $page_no, $page_num);

        if ($dealer_address_list) {
            foreach ($dealer_address_list as $k => $v) {

                $province_info = area_helper::get_area_info($v['province_code']);
                if ($province_info) {
                    $province_name = $province_info['area'];
                } else {
                    $province_name = '';
                }

                $city_info = _uri('region', array('area_code' => $v['city_code']));

                if ($city_info) {
                    $city_name = $city_info['area'];
                    $dealer_address_list[$k]['city_name'] = $city_name;
                    $county_info = area_helper::get_area_info($v['county_code']);

                    if ($county_info) {
                        $county_name = $county_info['area'];
                        $dealer_address_list[$k]['county_name'] = $county_name;
                    }
                }

                $dealer_address_list[$k]['province_name'] = $province_name;
            }

            return $dealer_address_list;

        } else {
            //             $default_dealer_address = _uri('dealer_address', array('user_id' => $dealer_id, 'is_default' => 1));
            //             if (!$default_dealer_address) {

            //                 // 说明合伙人的默认地址还没有存入到关系表中
            //                 if (!$user_info) {
            //                     return array();
            //                 }
            //                 $area_tree_info = _widget('area')->get_area_info_by_area_code($user_info['area_code']);
            //                 $dealer_address_info = array();

            //                 if (isset($area_tree_info['county_info'])) {
            //                     $dealer_address_info['county_code']   = $area_tree_info['county_info']['area_code'];
            //                     $dealer_address_info['city_code']     = $area_tree_info['city_info']['area_code'];
            //                     $dealer_address_info['province_code'] = $area_tree_info['province_info']['area_code'];

            //                 } elseif (isset($area_tree_info['city_info'])) {
            //                     $dealer_address_info['city_code']     = $area_tree_info['city_info']['area_code'];
            //                     $dealer_address_info['province_code'] = $area_tree_info['province_info']['area_code'];

            //                 } elseif (isset($area_tree_info['province_info'])) {
            //                     $dealer_address_info['province_code'] = $area_tree_info['province_info']['area_code'];
            //                 }

            //                 $dealer_address_info['is_default'] = 1;
            //                 $dealer_address_info['add_time'] = date('Y-m-d H:i:s');
            //                 $dealer_address_info['update_time'] = date('Y-m-d H:i:s');
            //                 $dealer_address_info['dealer_address'] = $user_info['store_house'];
            //                 $dealer_address_info['user_id'] = $dealer_id;

            //                 _model('dealer_address')->create($dealer_address_info);
            //                 // 递归
            //                 return dealers_helper::get_dealer_address_list($dealer_id, $page_no, $page_num);
            //             }
        }
    }

    /**
     * 获取合伙人的地区信息
     *
     * @param null $dealer_ids
     * @return array
     * @throws AnException
     */
    public static function get_dealers_location($dealer_ids = null) {

        $filter = array();
        $filter['is_default'] = 1;
        //$filter['status'] = 1;

        if (is_numeric($dealer_ids) && $dealer_ids > 0) {
            $dealers = array($dealer_ids);
            $filter['user_id'] = $dealers;
        } elseif (is_array($dealer_ids) && !empty($dealer_ids)) {
            $dealers = $dealer_ids;
            $filter['user_id'] = $dealers;
        } else {
            $dealer_filter = array('dealer_level' => array(1, 2), 'is_enable' => 1);
            $dealers = _model('user')->getFields('id', enable_filter($dealer_filter));
        }

        $address_list = array_to_filelds_assoc('user_id', _model('dealer_address')->getList($filter));

        $index = array();
        foreach ($dealers as $dealer_id) {
            if (array_key_exists($dealer_id, $address_list) && !empty($address_list)) {
                $index[$dealer_id] = array(
                    $address_list[$dealer_id]['province_code'],
                    $address_list[$dealer_id]['city_code'],
                    $address_list[$dealer_id]['county_code'],
                );
            } else {
                $index[$dealer_id] = array('', '', '');
            }
        }

        return $index;
    }

    /**
     * 获取合伙人的市场人员列表
     *
     * @param int $agency_id
     * @return array
     * @throws AnException
     */
    public static function get_marketing_list_by_agency_id($agency_id = 0) {
        if ($agency_id > 0) {

            $marketing_ids = _model('user_marketing')->getFields('marketing_id', array('agency_id' => $agency_id));

            if (count($marketing_ids)) {
                return _model('user')->getList(array('id' => $marketing_ids));
            }
        }

        return array();
    }
}
